<template>
  <view>
    <view class="navbar">
      <uni-nav-bar @clickLeft="goback" leftIcon="left" fixed="true" border="false" color="#FFF" statusBar="true"
        backgroundColor="#22b9a3" :title="title" />
    </view>

    <view class="content">
      <uni-forms :modelValue="formData">
        <uni-row>
          <uni-col :span="16" offset=1>
            <uni-forms-item label="姓名" name="name" required>
              <uni-easyinput type="text" v-model="formData.name" placeholder="请填写您的姓名" all />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="16" offset=1>
            <uni-forms-item label="手机号" name="phone" required>
              <uni-easyinput type="number" v-model="formData.mobile" placeholder="请填写您的手机号" all maxlength="11" />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="16" offset=1>
            <uni-forms-item label="城市" name="cityCode" required labelWidth="150rpx">
              <uni-data-picker v-model="formData.areaId"	 @change="fetchCity" placeholder="请选择省份" popup-title="请选择城市" :map="map"
                :localdata="cityList" />
            </uni-forms-item>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="4" offset=1>
            <div class="self">
              <uni-forms-item label="详细地址" name="brief" required labelWidth="80">
              </uni-forms-item>
            </div>
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="16" offset=1>
            <textarea v-model="formData.detailAddress" placeholder="请填入详细地址" maxlength="200" class="selfcontent" />
          </uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="16" offset=1>
            <uni-forms-item label="是否设为默认地址" name="defaultStatus" label-width="250rpx">
              <switch :checked="formData.defaultStatus" @change="switchStatus" style="transform:scale(0.7)" />
            </uni-forms-item>
          </uni-col>
        </uni-row>
      </uni-forms>
    </view>
    <view class="card" @click="submitInfo">
      <view class="btn">保存地址</view>
    </view>
  </view>
</template>

<script setup>
  import * as http from '@/utils/http'
  import {
    showToastAndDo
  } from '@/utils/toast.js'
  import {
    ref,
    onMounted
  } from 'vue'
  import {
    useUserInfo
  } from '@/stores/userinfo.js';
  import {
    useSwitch
  } from '@/stores/switch.js'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  const title = ref()
  const formData = ref({defaultStatus:true})
  onLoad(async (option) => {
    //判断登录信息
    if (Number.isFinite(+option.id)) {
      title.value = '修改地址'
      formData.value.id = option.id
      const result = await http.getRequest("/member/address/get", {
        id: option.id
      })
      if (result.code == 0) {
        formData.value = result.data
      } else {
        uni.showToast({
          title: '获取地址信息失败',
          icon: 'error',
          duration: 1000
        })
      }
    } else {
      title.value = '添加地址'
    }
  const cityResult = await http.getRequest("/system/area/tree")
    if (cityResult.code == 0) {
      cityList.value = cityResult.data
    }
  })
    
  const status = [{
    text: '是',
    value: 1
  }, {
    text: '否',
    value: 2
  }];
  const map = {
    text: 'name',
    value: 'id'
  }
  const cityList = ref([])

  function goback() {
    uni.navigateBack()
  }
  //获取选择的城市
  function fetchCity(e) {
    formData.value.areaId = e.detail.value[2].value
  }

  //是否为默认地址
  function switchStatus(e) {
    formData.value.defaultStatus = e.detail.value
  }

  async function submitInfo() {

    if (validateForm()) {
      if (formData.value.id) {
        const result = await http.putRequest('/member/address/update', formData.value)
        if (result.code == 0) {
          showToastAndDo('修改成功', 'success', 1000, () => {
            uni.navigateBack()
          })
        }
      } else {
        const result = await http.postRequest('/member/address/create', formData.value)
        if (result.code == 0) {
          showToastAndDo('添加成功', 'success', 1000, () => {
            uni.navigateBack()
          })
        } else if (result.code == 1001000011) {
          showToastAndDo(result.msg, 'error', 1000, () => {})
        }
      }
      //返回后需要重新加载数据
      useSwitch().controlReloadAddress(true)
    }

  }

  function validateForm() {
    const {
      name,
      mobile,
      areaId,
      detailAddress

    } = formData.value
    // 姓名校验（简单示例，实际可能更复杂）  
    if (!name || name.trim() === '') {
      uni.showToast({
        title: '姓名不能为空',
        icon: 'none'
      });
      return false;
    }
    // 手机号校验  
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      uni.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return false;
    }
 if (!detailAddress || detailAddress.trim() === '') {
      uni.showToast({
        title: '详细地址不能为空',
        icon: 'none'
      });
      return false;
    }
    return true;
  }
</script>

<style lang="scss" scoped>
  .navbar ::v-deep .uni-nav-bar-text {
    font-size: $uni-font-size-title !important;
    font-family: "siyuan";
  }

  ::v-deep .uni-row {
    margin-top: 20rpx;
  }

  .selfcontent {
    /* 设置边框样式 */
    border: 1rpx solid #f5f5f5;
    /* 边框宽度、样式和颜色 */
    /* 你可以根据需要添加更多样式 */
    border-radius: 15rpx;
    /* 边框圆角 */
    padding: 10px;
    /* 内边距 */
    height: 100rpx;
    /* 高度 */
    background-color: #e5e5e5;
  }

  .card {
    bottom: 10rpx;
    width: 100%;
    text-align: center;
    padding: 20rpx;
    border-radius: 10rpx;
  }


  .btn {
    margin: 10rpx;
    padding: 10rpx 40rpx;
    width: 80%;
    height: 50rpx;
    line-height: 50rpx;
    background-color: #22b9a3;
    color: #fff;
    border-radius: 50rpx;
    text-align: center;
    font-size: 35rpx;
  }
</style>